package com.lc.cehui.ui.fragment.order;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.lc.cehui.R;
import com.lc.cehui.app.AppFragment;
import com.lc.cehui.base.BaseDialog;
import com.lc.cehui.dialog.MessageDialog;
import com.lc.cehui.http.glide.GlideApp;
import com.lc.cehui.http.request.OrderDelApi;
import com.lc.cehui.http.request.OrderListApi;
import com.lc.cehui.http.response.BaseBean;
import com.lc.cehui.http.response.OrderButtonBean;
import com.lc.cehui.http.response.OrderListBean;
import com.lc.cehui.other.IntentKey;
import com.lc.cehui.ui.activity.OrderDetailsActivity;
import com.lc.cehui.ui.activity.OrderListActivity;
import com.lc.cehui.util.SPUtil;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

public class OrderListFragment extends AppFragment<OrderListActivity> {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.layout_refresh)
    TwinklingRefreshLayout refreshLayout;
    private BaseQuickAdapter adapter;
    private static final String TAG = "OrderListFragment";
    private static final String ARG_PARAM1 = "param1";
    private String system_id = "";
    private int page = 1;
    private String flag;
    private List<OrderListBean.DataBean> dtsu = new ArrayList<>();
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_orderlist;
    }
    public static OrderListFragment newInstance(String system_id) {
        OrderListFragment fragment = new OrderListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, system_id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
//        一级adapter
        adapter = new BaseQuickAdapter<OrderListBean.DataBean, BaseViewHolder>(R.layout.item_shop_order, dtsu) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, OrderListBean.DataBean item) {
                helper.setText(R.id.tv_statetype, getType(item.getState()));
                helper.setText(R.id.tv_statetype,item.getName());
                helper.setText(R.id.tv_total_number,"共"+item.getTotal_num()+"件商品 合计：￥");
                helper.setText(R.id.total_price,item.getTotal_money()+"");
                helper.setText(R.id.tv_total_yunfei,"(含运费￥"+item.getFreight()+")");
                RecyclerView rv_button = helper.getView(R.id.rv_button);

                List<OrderButtonBean> bts = new ArrayList<>();
//                0=待付款,1=待发货,2=待收货,3=待评价,4=待返还 6退货退款
                if (item.getState() == 0) {
                    bts.add(new OrderButtonBean("付款", Color.parseColor("#FFffffff"), R.drawable.jhx_selector_yj_jx_blue,
                            view -> {
                                startActivity(new Intent(getContext(), OrderDetailsActivity.class)
                                        .putExtra("order_id", item.getOrder_id())
                                        .putExtra("state", item.getState()));
                            }));
                    bts.add(new OrderButtonBean("取消订单", Color.parseColor("#c1c1c1"), R.drawable.jhx_yuanjiao_juxing_gray1,
                            view -> {
//                            取消订单
                                new MessageDialog.Builder(getActivity())
                                        // 标题可以不用填写
                                        .setTitle("取消订单")
                                        // 内容必须要填写
                                        .setMessage("您是否要取消该订单？")
                                        // 确定按钮文本
                                        .setConfirm(getString(R.string.common_confirm))
                                        // 设置 null 表示不显示取消按钮
                                        .setCancel(getString(R.string.common_cancel))
                                        // 设置点击按钮后不关闭对话框
                                        //.setAutoDismiss(false)
                                        .setListener(new MessageDialog.OnListener() {

                                            @Override
                                            public void onConfirm(BaseDialog dialog) {
                                                order_del(item.getOrder_id()+"");

                                            }

                                            @Override
                                            public void onCancel(BaseDialog dialog) {
                                                dialog.dismiss();
                                            }
                                        })
                                        .show();

                            }));

                } else if (item.getState() == 1) {

                    bts.add(new OrderButtonBean("申请退款", Color.parseColor("#FFffffff"), R.drawable.jhx_selector_yj_jx_blue,
                            view -> {

                            }));

                } else if (item.getState() == 2) {
                    bts.add(new OrderButtonBean("申请退款", Color.parseColor("#FF333333"), R.drawable.jhx_yuanjiao_juxing_gray1,
                            view -> {
//                              申请退款

                            }));
                    bts.add(new OrderButtonBean("确认收货", Color.parseColor("#FFffffff"), R.drawable.jhx_selector_yj_jx_blue,
                            view -> {
//                              确认收货

                            }));

                } else if (item.getState() == 3) {
                    bts.add(new OrderButtonBean("评价", Color.parseColor("#FFffffff"), R.drawable.jhx_selector_yj_jx_blue,
                            view -> {
//                               评价

                            }));


                } else if (item.getState() == 4||item.getState() == 5||item.getState() == 6) {
                    bts.add(new OrderButtonBean("再次购买", Color.parseColor("#FFffffff"), R.drawable.jhx_selector_yj_jx_blue,
                            view -> {

                            }));

                } else if (item.getState() == 7||item.getState() == 8) {
                    bts.add(new OrderButtonBean("查看详情", Color.parseColor("#FFffffff"), R.drawable.jhx_selector_yj_jx_blue,
                            view -> {

                            }));

                }

                item.setBts(bts);

                rv_button.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }

                    @Override
                    public boolean canScrollHorizontally() {
                        return false;
                    }
                });
                rv_button.setAdapter(new BaseQuickAdapter<OrderButtonBean, BaseViewHolder>(R.layout.item_order_button,
                        item.getBts()) {

                    @Override
                    protected void convert(BaseViewHolder viewHolder, OrderButtonBean orderButtonBean) {
                        viewHolder.setText(R.id.text, orderButtonBean.getText());
                        viewHolder.setTextColor(R.id.text, orderButtonBean.getTextColor());
                        viewHolder.setBackgroundResource(R.id.text, orderButtonBean.getBgDrawable());
                        viewHolder.getView(R.id.text).setOnClickListener(orderButtonBean.getOnClickListener());
                    }
                });
                //          二级adapter
                RecyclerView rv_order_goods = helper.getView(R.id.rv_order_goods);
                BaseQuickAdapter<OrderListBean.DataBean.StoreOrderListBean, BaseViewHolder> goodsAdp = new BaseQuickAdapter<OrderListBean.DataBean.StoreOrderListBean, BaseViewHolder>(R.layout.item_order_goods, item.getStore_order_list()) {
                    @Override
                    protected void convert(@NonNull BaseViewHolder helper, OrderListBean.DataBean.StoreOrderListBean item) {
                        helper.setText(R.id.tv_shop_name, item.getGoods_name());
                        helper.setText(R.id.tv_spec, "型号："+item.getGoods_attr());
                        helper.setText(R.id.tv_price, "¥"+item.getGoods_price());
                        helper.setText(R.id.tv_num, "x"+item.getGoods_num());
                        GlideApp.with(getActivity())
                                .load(item.getPicurl())

                                .into((ImageView) helper.getView(R.id.img));




                    }
                };

                rv_order_goods.setAdapter(goodsAdp);
                goodsAdp.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        startActivity(new Intent(getContext(), OrderDetailsActivity.class)
                                .putExtra("order_id", item.getOrder_id())
                                .putExtra("state", item.getState()));
                    }
                });

            }
        };
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(getContext(), OrderDetailsActivity.class)
                        .putExtra("order_id", dtsu.get(position).getOrder_id())
                        .putExtra("state", dtsu.get(position).getState()));
            }
        });
        recyclerView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                page = 1;
                dtsu.clear();
                order_list();
                refreshLayout.finishRefreshing();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);

                refreshLayout.finishLoadmore();

 if (flag.equals("T")) {
                    page++;
                    order_list();
     refreshLayout.setEnableLoadmore(true);
                } else {
                    refreshLayout.setEnableLoadmore(false);

                }
            }
        });
        showEmptyView(adapter);
    }

    private void order_del(String order_id) {
        EasyHttp.post(this)
                .api(new OrderDelApi().setUserid(SPUtil.get(getContext(), IntentKey.USERID, 0)).setOrder_id(order_id))
                .request(new HttpCallback<BaseBean>(this) {
                    @Override
                    public void onSucceed(BaseBean data) {

                        if (callBackCode(data)) {
                            page = 1;
                            dtsu.clear();
                            order_list();



                        }
                    }
                });
    }

    @Override
    protected void initData() {

    }
    @Override
    public void onResume() {
        super.onResume();
//
        if (getArguments() != null) {
            system_id = getArguments().getString(ARG_PARAM1);
            page = 1;
            dtsu.clear();
            order_list();
        }
    }
    private String getType(int type) {
        String res = "";//订单状态(0未支付,1支付成功,2配餐中,4配送中,5已存柜,6已接收,7已失效,8已删除(用户不可见))9 无柜存餐待确认 10 已取消 11 失效已取出12支付失败
        switch (type) {
            case 0:
                res = "待付款";
                break;
            case 1:
                res = "待发货";
                break;
            case 2:
                res = "待收货";
                break;
            case 3:
                res = "待评价";
                break;
            case 4:
                res = "已完成";
                break;
            case 5:
                res = "已取消";
                break;
            case 6:
                res = "已退款";
                break;
            case 7:
                res = "退款中";
                break;
            case 8:
                res = "已拒绝";
                break;
        }
        return res;
    }
    private void order_list() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                EasyHttp.post(new ApplicationLifecycle())
                        .api(new OrderListApi().setUserid(SPUtil.get(getContext(), IntentKey.USERID, 0)).setPage(page).setType(system_id)
                        ).request(new OnHttpListener<OrderListBean>() {


                    @Override
                    public void onSucceed(OrderListBean data) {
                        flag = data.getFlag();
                        dtsu.addAll(data.getData());
                        adapter.setNewData(dtsu);
                        adapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onFail(Exception e) {
                        refreshLayout.finishRefreshing();
                    }
                });
            }
        }, 100);
    }

}
